package com.geek.water.security;

import com.geek.water.entity.*;
import com.geek.water.mapper.UserMapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
@Slf4j
@RequiredArgsConstructor
public class SecurityUserDetailsService implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MPJLambdaWrapper<User> wrapper = new MPJLambdaWrapper<>();

        wrapper.selectAll(User.class)
                .selectCollection(Role.class, User::getRoles,
                        roleBuilder -> roleBuilder
                                .collection(Permission.class, Role::getPermissions)  // ← 用 collection(...)
                )
                .leftJoin(UserRole.class, on -> on.eq(UserRole::getUserId, User::getId))
                .leftJoin(Role.class, on -> on.eq(Role::getId, UserRole::getRoleId))
                .leftJoin(RolePermission.class, on -> on.eq(RolePermission::getRoleId, Role::getId))
                .leftJoin(Permission.class, on -> on.eq(Permission::getId, RolePermission::getPermissionId))
                .eq(StringUtils.hasText(username), User::getUsername, username);

        User user = userMapper.selectJoinOne(User.class, wrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        return new LoginUser(user);
    }
}